import "./types";

import type { App } from "vue";
import { createRouter, createWebHashHistory } from "vue-router/auto";

import { useUserStore } from "@/stores/user";
import { routes } from "vue-router/auto-routes";

const genRoutes = () => {
	return [
		routes.find((e) => e.path === "/login")!,
		{
			path: "/",
			name: "BasicLayout",
			component: () => import("@/layouts").then((e) => e.BasicLayout),
			children: routes.filter((item) => item.path !== "/login"),
		},
		// 404自动跳转到主页
		{
			path: "/:pathMatch(.*)*",
			redirect: "/",
		},
	];
};

/**
 *
 * 根据路径自动生成定制化路由
 * unplugin-vue-router
 * https://github.com/posva/unplugin-vue-router
 * https://uvr.esm.is/
 */

export const router = createRouter({
	history: createWebHashHistory("/base"),
	routes: genRoutes(),
});

router.beforeEach(async (to, _from, next) => {
	const userStore = useUserStore();

	if (to.name !== "LoginPage" && !userStore.isLogined) {
		return next({ name: "LoginPage" });
	}
	try {
		if (userStore.isLogined && !userStore.userInfo?.userId) {
			await userStore.getUserInfo();
		}
	} catch (error) {
		console.error(error);
	}

	//   if (
	//     to.matched.filter((e) => e.path === "/company").length &&
	//     userStore.userType !== "1"
	//   ) {
	//     return next({ path: "/" });
	//   }

	if (
		to.matched.filter((e) => e.path === "/park").length &&
		userStore.userType !== "2"
	) {
		return next({ path: "/" });
	}

	if (to.path === "/" && ["1", "2"].includes(userStore.userType!)) {
		return next({
			path: userStore.userType === "1" ? "/company/home" : "/park/home",
		});
	}
	return next();
});

export function setupRouter(app: App) {
	return app.use(router);
}
